import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/pages/home/index.dart';
import 'package:flutter_enjoy_plus/pages/mine/index.dart';
import 'package:flutter_enjoy_plus/utils/EventBus.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({super.key});

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  @override
  void initState() {
    tokenManager.initToken();
    super.initState();
    ListenEvnet();
  }

  ListenEvnet() {
    eventBus.on<LogoutEventBus>().listen((event) {
      // 跳转至登录页面
      // Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
      Navigator.pushNamed(context, '/login');
    });
  }

  // 底部tabbar List
  final List _tabbarList = [
    {
      'label': '首页',
      'icon': 'assets/tabs/home_default.png',
      'activeIcon': 'assets/tabs/home_active.png',
    },
    {
      'label': '我的',
      'icon': 'assets/tabs/my_default.png',
      'activeIcon': 'assets/tabs/my_active.png',
    }
  ];
  // 底部tabbar 当前选中的index
  int _currentIndex = 0;

  // 第一种方案 --> 通过index来判断显示哪个页面
  // getTabbarContent() {
  //   if (_currentIndex == 0) {
  //     return const HomePage();
  //   } else if (_currentIndex == 1) {
  //     return MinePage(currentIndex: _currentIndex);
  //   }
  // }
  // 第二种方案 -> (性能更优) IndexStacked -> 通过index 指定渲染 (不会每次都销毁重建)

  // changeIndex
  changeIndex(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  // 封装 获取底部TabsItem 内容
  List<BottomNavigationBarItem> getBottomNavigationBarItems() {
    List<BottomNavigationBarItem> list = [];
    for (var item in _tabbarList) {
      list.add(BottomNavigationBarItem(
          icon: Image.asset(item['icon'], width: 30, height: 30),
          label: item['label'],
          activeIcon: Image.asset(item['activeIcon'], width: 30, height: 30)));
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // SafeArea 安全区组件
      body: SafeArea(
        child: IndexedStack(
          index: _currentIndex,
          children: [const HomePage(), MinePage(currentIndex: _currentIndex, changeIndex: changeIndex)],
        ),
      ),
      // 底部的tabbar TODO
      bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          currentIndex: _currentIndex,
          selectedItemColor: const Color.fromRGBO(99, 144, 174, 1),
          unselectedItemColor: Colors.black,
          items: getBottomNavigationBarItems(),
          onTap: (int index) {
            setState(() {
              _currentIndex = index;
            });
          }),
    );
  }
}
